#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This program is part of pygimli
Visit http://www.resistivity.net for further information or the latest version.
"""

import sys
import os
import pygimli as pg


def main(argv):

    import argparse

    # intialisize parser
    parser = argparse.ArgumentParser(description="Merge two meshes")

    # define some options (better import from defaultParser)
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
                        help="Be verbose")
    parser.add_argument("--debug", dest="debug", action="store_true",
                        help="debug mode")
    parser.add_argument('meshes', type=str, nargs='+',
                        help='Files to be merge. If there are more than 2 files, '
                        ' e.g., called with wildcard (*.vtk), the file matches '
                        'the outFileName will be excluded.')
    parser.add_argument("-o", dest="outFileName", type=str,
                        help="Filename for the resulting mesh.",
                        default='merged')

    args = parser.parse_args()
    if args.debug:
        pg.setDebug(args.debug)

    if args.verbose:
        print(args)

    if len(args.meshes) < 2:
        print("Need at least 2 meshes to merge")
        sys.exit()

    (outfileBody, fileExtension) = os.path.splitext(args.outFileName)

    if len(args.meshes) > 2:
        args.meshes = list(filter(lambda m: outfileBody not in m, args.meshes))

    mesh = pg.meshtools.mergeMeshes(args.meshes, args.verbose)

    if args.verbose:
        print("Save:")
        print(outfileBody, mesh)

    if outfileBody.find('.vtk'):
        mesh.exportVTK(outfileBody)
        if args.verbose:
            print("write out: ", outfileBody + ".vtk")
    else:
        mesh.saveBinaryV2(outfileBody)
        if args.verbose:
            print("write out: ", outfileBody + ".bms")


if __name__ == "__main__":
    main(sys.argv[1:])
